var net  = require('net');
var http = require('http');

var contenido = 'inicial';
var buffer	  = null;

var SOCKET_TIMEOUT = 15000;

var httpServer = http.createServer (function (req, res) {
  res.writeHead	(200, {'Content-Type': 'text/plain'});
  res.end		(contenido);
});

var tcpServer = net.createServer (function (sock) {
	var remoteAddress	= sock.remoteAddress;
	var remotePort		= sock.remotePort	;
	var acumData		= "";
	var letra			= "";
	
	console.log ('conec ' + remoteAddress + ' ' + remotePort + ' ' + tcpServer.connections);
	
	// Evento data
    sock.on ('data', function (data) {
		var i = 0;
		
		for (i = 0; i < data.length; ++ i) {
			letra		=	String.fromCharCode (data[i]);
			acumData	+=	letra;
			
			if (letra == ';') {
				console.log ('data ' + sock.remoteAddress + ' ' + sock.remotePort + ' ' + acumData);
				contenido	= acumData;
				buffer		= null;
				buffer      = new Buffer (acumData);
				console.log ("============>>>>>>> " + buffer.length);
				acumData	= '';
			}
		}
    });
    
	// Evento close
    sock.on ('close', function (data) {
        console.log	('close ' + remoteAddress + ' ' + remotePort  + ' ' + tcpServer.connections);
    });
    
	// Evento error
	sock.on ('error', function (error) {
		console.log	('error ' + remoteAddress + ' ' + remotePort + ' ' + error);
		sock.destroy();
	});	
	
	// Seteo el timeout para este socket...		
	sock.setTimeout (SOCKET_TIMEOUT, function () {
		console.log ('timedout ' + remoteAddress + ' ' + remotePort);
		sock.destroy();
	});
});

tcpServer	.listen	(1338);
httpServer	.listen	(1337);
